﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.ExtraInformation;
using Microsoft.Practices.EnterpriseLibrary.Logging.Filters;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;

namespace BesAsm.Framework.Reporting
{
  public delegate void MessageReportedEventHandler(object sender, MessageReportedArgs e);

  public static class Messenger
  {
    private static Queue<ReportableMessage> _messages = new Queue<ReportableMessage>();
    internal static event MessageReportedEventHandler MessageQueued;
    private static LogWriter _logWriter;

    static Messenger()
    {

    }

    public static void ReportMessage(string message, ReportableMessageType messageType)
    {
      ReportableMessage rm = new ReportableMessage();
      rm.Description = message;
      rm.MessageType = messageType;
      _messages.Enqueue(rm);

      if (MessageQueued != null)
      {
        MessageQueued(null, new MessageReportedArgs(rm));
      }
    }

    private static void messenger_MessageReported(object sender, MessageReportedArgs e)
    {
      _messages.Enqueue(e.Message);
      OnMessageQueued(e);
    }

    internal static void OnMessageQueued(MessageReportedArgs e)
    {
      if (MessageQueued != null)
        MessageQueued(null, e);
    }

    internal static ReportableMessage GetMessage()
    {
      if (_messages.Count > 0)
      {
        ReportableMessage message = _messages.Dequeue();
        LogEntry log = new LogEntry()
        {
          Message = message.Description

        };

        if (_logWriter == null)
          _logWriter = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
        _logWriter.Write(log);
        return message;
      }
      else
        return null;
    }

    internal static int MessageCount { get { return _messages.Count; } }
  }
}
